<template>
  <div class="callback-container">
    <div class="callback-content">
      <div v-if="loading" class="loading">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
        <p>正在处理微信登录...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <el-icon>
          <WarningFilled />
        </el-icon>
        <p>{{ error }}</p>
        <el-button type="primary" @click="goToLogin">返回登录</el-button>
      </div>
      
      <div v-else class="success">
        <el-icon>
          <SuccessFilled />
        </el-icon>
        <p>登录成功，正在跳转...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { Loading, WarningFilled, SuccessFilled } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref(true)
const error = ref('')

// 处理微信登录回调
const handleWxCallback = async () => {
  try {
    const code = route.query.code as string
    const state = route.query.state as string
    
    if (!code) {
      throw new Error('未获取到授权码，请重新登录')
    }
    
    console.log('微信回调参数:', { code, state })
    
    // 调用后端微信登录接口
    const response = await fetch(`/wechat/login/wx_open?code=${code}&state=${state || ''}`)
    const result = await response.json()
    
    if (result.code === 0 && result.data) {
      // 登录成功
      const { accessToken, userId } = result.data
      
      // 创建用户信息对象
      const userInfo = {
        id: userId,
        username: `wx_user_${userId}`,
        nickname: '微信用户',
        email: '',
        status: 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      }
      
      // 保存登录状态
      userStore.login(accessToken, userInfo)
      
      ElMessage.success('微信登录成功')
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.replace('/')
      }, 1000)
      
    } else {
      throw new Error(result.msg || '微信登录失败')
    }
    
  } catch (err) {
    console.error('微信登录回调处理失败:', err)
    error.value = err instanceof Error ? err.message : '登录处理失败'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 返回登录页
const goToLogin = () => {
  router.replace('/login')
}

// 页面加载时处理回调
onMounted(() => {
  // 检查是否有错误参数
  if (route.query.error) {
    error.value = '用户取消授权或授权失败'
    loading.value = false
    return
  }
  
  // 处理微信回调
  handleWxCallback()
})
</script>

<style scoped lang="scss">
.callback-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.callback-content {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  text-align: center;
  min-width: 300px;
}

.loading, .error, .success {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.loading .el-icon {
  font-size: 32px;
  color: #409eff;
}

.error .el-icon {
  font-size: 32px;
  color: #f56c6c;
}

.success .el-icon {
  font-size: 32px;
  color: #67c23a;
}

p {
  margin: 0;
  font-size: 16px;
  color: #606266;
}
</style>
